package com.xiangxiao.rpan.storage.download.channel;

import com.xiangxiao.rpan.storage.core.DownloadFileTool;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/12/1 17:41
 */
@Component(value = "downloadFileChannel")
public class DownloadFileChannel implements DownloadFileTool {

  @Override
  public void readStreamToFile(String path, HttpServletResponse response) throws IOException {
    File file = new File(path);
    long downloadSize = file.length();

    //注意下面设置的相关请求头
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    //相当于设置请求头content-length
    response.setContentLengthLong(downloadSize);

    //使用URLEncoder处理中文名(否则会出现乱码)
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    FileChannel inChannel = randomAccessFile.getChannel();
    WritableByteChannel outChannel = Channels.newChannel(response.getOutputStream());

    try {
      while (downloadSize > 0) {
        long count = inChannel.transferTo(0, downloadSize, outChannel);
        if (count > 0) {
          downloadSize -= count;
        }
      }
      inChannel.close();
      outChannel.close();
      randomAccessFile.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public String convertMuitlFileToStream(MultipartFile multipartFile, Integer chunkNumber, Integer totalChunks, long blockSize) {
    // todo
    return null;
  }
}
